import 'dart:io';
import 'dart:typed_data';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:file_picker/file_picker.dart';

/// 文件工具类
class FileUtils {
  /// 获取文件扩展名
  static String getFileExtension(String format) {
    switch (format.toLowerCase()) {
      case 'png':
        return '.png';
      case 'jpg':
      case 'jpeg':
        return '.jpg';
      case 'bmp':
        return '.bmp';
      default:
        return '.png';
    }
  }

  /// 获取安全的文件名
  static String getSafeFilename(String filename) {
    // 移除不安全的字符
    return filename.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
  }

  /// 获取唯一的文件名
  static String getUniqueFilename(String directory, String filename) {
    String baseName = path.basenameWithoutExtension(filename);
    String extension = path.extension(filename);
    String fullPath = path.join(directory, filename);
    int counter = 1;

    while (File(fullPath).existsSync()) {
      filename = '${baseName}_$counter$extension';
      fullPath = path.join(directory, filename);
      counter++;
    }

    return filename;
  }

  /// 选择保存目录
  static Future<String?> selectSaveDirectory() async {
    if (Platform.isAndroid || Platform.isIOS) {
      // 移动平台使用应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      return directory.path;
    } else {
      // 桌面平台使用文件选择器
      String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
      return selectedDirectory;
    }
  }

  /// 打开目录
  static Future<void> openDirectory(String path) async {
    if (Platform.isAndroid || Platform.isIOS) {
      // 移动平台暂不支持打开目录
      return;
    }

    try {
      if (Platform.isMacOS) {
        await Process.run('open', [path]);
      } else if (Platform.isWindows) {
        await Process.run('explorer', [path]);
      } else if (Platform.isLinux) {
        await Process.run('xdg-open', [path]);
      }
    } catch (e) {
      print('打开目录失败: $e');
    }
  }

  /// 保存文件
  static Future<String?> saveFile(
    Uint8List data,
    String? directory,
    String? filename,
    String format,
  ) async {
    try {
      final saveDir =
          directory ?? (await getApplicationDocumentsDirectory()).path;
      final ext = getFileExtension(format);
      String name = getSafeFilename(filename ?? 'color_block');
      name = getUniqueFilename(saveDir, '$name$ext');

      final file = File(path.join(saveDir, name));
      await file.writeAsBytes(data);

      return file.path;
    } catch (e) {
      print('保存文件失败: $e'); // 使用 debugPrint 代替 print，仅在调试模式下输出
      return null;
    }
  }
}
